<template>
  <div class="overview-container">
    <!-- 统一标题样式 -->
    <div class="header-section">
      <h2>数据概览</h2>
      <div class="title-line"></div>
    </div>
    
    <div class="stat-cards">
      <!-- 用户总数卡片 -->
      <el-card class="stat-card">
        <div class="card-content">
          <div class="card-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">总用户数</div>
            <div class="card-value">{{ userCount }}</div>
          </div>
        </div>
      </el-card>
      
      <!-- 日均活跃用户量卡片 -->
      <el-card class="stat-card">
        <div class="card-content">
          <div class="card-icon activity-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">日均活跃用户 (30天)</div>
            <div class="card-value">{{ dau.toFixed(1) }}</div>
            <div class="card-description">基于答题记录统计</div>
          </div>
        </div>
      </el-card>
      
      <!-- 人均做题量卡片 -->
      <el-card class="stat-card">
        <div class="card-content">
          <div class="card-icon questions-icon">
            <el-icon><Document /></el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">人均做题量 (30天)</div>
            <div class="card-value">{{ avgQuestions.toFixed(1) }}</div>
            <div class="card-description">基于答题记录统计</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 新增用户增长趋势图表 -->
    <el-card class="chart-card">
      <div class="chart-header">
        <div class="header-gradient"></div>
        <h3>用户增长趋势</h3>
        <div class="time-tabs">
          <el-radio-group v-model="growthTimeRange" @change="fetchUserGrowthData">
            <el-radio-button label="daily">日增长</el-radio-button>
            <el-radio-button label="weekly">周增长</el-radio-button>
            <el-radio-button label="monthly">月增长</el-radio-button>
            <el-radio-button label="yearly">年增长</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div class="chart-container">
        <div ref="growthChart" style="width: 100%; height: 400px;"></div>
      </div>
    </el-card>

    <!-- 图表容器 - 并排显示 -->
    <div class="chart-row">
      <!-- 科目答题比例饼图 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <div class="header-gradient"></div>
          <h3>科目答题比例</h3>
        </div>
        <div class="chart-container">
          <div ref="pieChart" style="width: 100%; height: 400px;"></div>
        </div>
      </el-card>

      <!-- 科目正确率柱状图 -->
      <el-card class="chart-card">
        <div class="chart-header">
          <div class="header-gradient"></div>
          <h3>科目答题正确率</h3>
        </div>
        <div class="chart-container">
          <div ref="barChart" style="width: 100%; height: 400px;"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { User, TrendCharts, Document } from '@element-plus/icons-vue'
import axios from 'axios'
import dayjs from 'dayjs'
import * as echarts from 'echarts'

export default {
  components: {
    User,
    TrendCharts,
    Document
  },
  setup() {
    // 原有统计卡片数据
    const userCount = ref(0)
    const dau = ref(0)
    const avgQuestions = ref(0)
    const loading = ref(false)
    const subjectStats = ref([])
    const correctRates = ref([])
    const pieChart = ref(null)
    const barChart = ref(null)
    
    // 新增用户增长趋势数据
    const growthChart = ref(null)
    const growthTimeRange = ref('monthly') // 默认显示月增长
    const growthData = ref([])

    // 获取用户总数
    const fetchUserCount = async () => {
      try {
        loading.value = true
        const response = await axios.get('/api/users/count')
        userCount.value = response.data
      } catch (error) {
        console.error('获取用户总数失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 获取日均活跃用户量
    const fetchDAU = async () => {
      try {
        const response = await axios.get('/api/statistics/last-30days-dau')
        dau.value = response.data || 0
      } catch (error) {
        console.error('获取日均活跃用户量失败:', error)
      }
    }

    // 获取人均做题量
    const fetchAvgQuestions = async () => {
      try {
        const endDate = dayjs().format('YYYY-MM-DD')
        const startDate = dayjs().subtract(30, 'day').format('YYYY-MM-DD')
        const response = await axios.get('/api/statistics/avg-questions', {
          params: { startDate, endDate }
        })
        avgQuestions.value = response.data || 0
      } catch (error) {
        console.error('获取人均做题量失败:', error)
      }
    }

    // 获取科目答题比例
    const fetchSubjectStats = async () => {
      try {
        const response = await axios.get('/api/statistics/subject-ratio')
        subjectStats.value = response.data.data || []
        initPieChart()
      } catch (error) {
        console.error('获取科目答题比例失败:', error)
      }
    }

    // 获取科目正确率
    const fetchCorrectRates = async () => {
      try {
        const response = await axios.get('/api/subject-stats/correct-rates')
        correctRates.value = response.data.data || []
        initBarChart()
      } catch (error) {
        console.error('获取科目正确率失败:', error)
      }
    }

    // 获取用户增长数据
    const fetchUserGrowthData = async () => {
      try {
    loading.value = true;
    const endpoint = `/api/analytics/user-growth/${growthTimeRange.value}`;
    const response = await axios.get(endpoint);
    console.log("API响应数据:", response.data); // 添加这行
    growthData.value = response.data || [];
    initGrowthChart();
  } catch (error) {
    console.error('获取用户增长数据失败:', error);
  } finally {
    loading.value = false;
  }
    }

    // 初始化饼图
    const initPieChart = () => {
      const chartDom = pieChart.value
      if (!chartDom) return
      
      const myChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: subjectStats.value.map(item => item.subjectName)
        },
        series: [
          {
            name: '答题比例',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: subjectStats.value.map(item => ({
              value: item.percentage,
              name: item.subjectName
            }))
          }
        ]
      }
      
      myChart.setOption(option)
      
      window.addEventListener('resize', function() {
        myChart.resize()
      })
    }

    // 初始化柱状图
    const initBarChart = () => {
      const chartDom = barChart.value
      if (!chartDom) return
      
      const myChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}<br/>正确率: {c}%'
        },
        xAxis: {
          type: 'category',
          data: correctRates.value.map(item => item.subjectName)
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [{
          name: '正确率',
          type: 'bar',
          data: correctRates.value.map(item => item.correctRate),
          itemStyle: {
            color: function(params) {
              const colorList = ['#5470C6', '#91CC75', '#EE6666']
              return colorList[params.dataIndex]
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}%'
          }
        }]
      }
      
      myChart.setOption(option)
      
      window.addEventListener('resize', function() {
        myChart.resize()
      })
    }

    // 初始化用户增长图表
const initGrowthChart = () => {
  const chartDom = growthChart.value;
  if (!chartDom) return;
  
  // 销毁旧实例
  let myChart = echarts.getInstanceByDom(chartDom);
  if (myChart) {
    myChart.dispose();
  }
  myChart = echarts.init(chartDom);
  
  // 准备图表数据 - 确保正确提取growth_rate
  const dates = growthData.value.map(item => item.date);
  const newUsers = growthData.value.map(item => item.count);
  const growthRates = growthData.value.map(item => {
    // 确保growth_rate是数字，null/undefined转为0
    const rate = Number(item.growth_rate);
    return isNaN(rate) ? 0 : rate;
  });

  console.log("图表准备数据:", {
    dates,
    newUsers, 
    growthRates
  }); // 调试输出

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      },
      formatter: function(params) {
        let result = params[0].axisValue + '<br/>';
        params.forEach(param => {
          const marker = param.marker;
          const seriesName = param.seriesName;
          const value = param.value;
          const unit = seriesName.includes('率') ? '%' : '';
          result += `${marker} ${seriesName}: ${value}${unit}<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: ['新增用户', '增长率']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: growthTimeRange.value === 'daily' ? 45 : 0
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '用户数',
        min: 0
      },
      {
        type: 'value',
        name: '增长率(%)',
        min: 0,
        axisLabel: {
          formatter: '{value}%'
        },
        // 动态设置y轴最大值，增加20%的余量
        max: Math.max(...growthRates) * 1.2 || 100
      }
    ],
    series: [
      {
        name: '新增用户',
        type: 'bar',
        data: newUsers,
        itemStyle: {
          color: '#5470C6'
        },
        barWidth: '60%'
      },
      {
        name: '增长率',
        type: 'line',
        yAxisIndex: 1, // 使用右侧y轴
        data: growthRates,
        itemStyle: {
          color: '#EE6666'
        },
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        }
      }
    ]
  };
  
  myChart.setOption(option);
  
  window.addEventListener('resize', function() {
    myChart.resize();
  });
}

    // 组件挂载时获取所有数据
    onMounted(() => {
      fetchUserCount()
      fetchDAU()
      fetchAvgQuestions()
      fetchSubjectStats()
      fetchCorrectRates()
      fetchUserGrowthData()
    })

    return {
  // 原有返回数据
  userCount,
  dau,
  avgQuestions,
  loading,
  pieChart,
  barChart,
  
  // 新增返回数据
  growthChart,
  growthTimeRange,
  fetchUserGrowthData
}
  }
}
</script>

<style scoped>
/* 整体布局和背景 */
.overview-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 标题区域 - 仿照用户管理页面 */
.header-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e9ed;
}

.header-section h2 {
  color: #1a2f54;
  font-weight: 600;
  font-size: 22px;
  margin-bottom: 8px;
}

.title-line {
  width: 50px;
  height: 4px;
  background: linear-gradient(90deg, #3b527a, #4e6694);
  border-radius: 2px;
}

/* 统计卡片样式 */
.stat-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  flex: 1;
  min-width: 250px;
  border-radius: 10px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 24px;
}

.card-icon {
  margin-right: 20px;
  padding: 16px;
  border-radius: 12px;
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(78, 102, 148, 0.3);
}

.activity-icon {
  background: linear-gradient(135deg, #67c23a 0%, #529b2e 100%);
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.questions-icon {
  background: linear-gradient(135deg, #e6a23c 0%, #d19d0b 100%);
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
}

.card-icon .el-icon {
  font-size: 28px;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  font-weight: 500;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #1a2f54;
  margin-bottom: 4px;
}

.card-description {
  font-size: 12px;
  color: #909399;
}

/* 图表卡片样式 */
.chart-row {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.chart-card {
  flex: 1;
  min-width: 0;
  border-radius: 10px;
  margin-bottom: 24px;
  border: none;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.chart-header {
  position: relative;
  padding: 16px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chart-header h3 {
  color: white;
  position: relative;
  z-index: 2;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  background: linear-gradient(135deg, #4e6694 0%, #3b527a 100%);
  z-index: 1;
}

.time-tabs {
  position: relative;
  z-index: 2;
}

/* 自定义单选按钮组样式 */
:deep(.time-tabs .el-radio-group) {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 4px;
}

:deep(.time-tabs .el-radio-button__inner) {
  background: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.8);
  padding: 8px 16px;
  font-size: 13px;
  border-radius: 4px;
  transition: all 0.3s;
}

:deep(.time-tabs .el-radio-button__original:checked + .el-radio-button__inner) {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  box-shadow: none;
}

:deep(.time-tabs .el-radio-button__inner:hover) {
  background: rgba(255, 255, 255, 0.15);
  color: white;
}

.chart-container {
  padding: 20px;
  background: white;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .chart-row {
    flex-direction: column;
  }
  
  .stat-cards {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .overview-container {
    padding: 16px;
  }
  
  .time-tabs {
    margin-top: 12px;
  }
  
  :deep(.time-tabs .el-radio-group) {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }
  
  :deep(.time-tabs .el-radio-button) {
    margin-bottom: 4px;
  }
  
  .card-content {
    padding: 20px;
  }
  
  .card-icon {
    padding: 12px;
  }
  
  .card-icon .el-icon {
    font-size: 24px;
  }
  
  .card-value {
    font-size: 24px;
  }
}

/* 增加一些微动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card,
.chart-card {
  animation: fadeInUp 0.6s ease-out;
}

.stat-card:nth-child(1) { animation-delay: 0.1s; }
.stat-card:nth-child(2) { animation-delay: 0.2s; }
.stat-card:nth-child(3) { animation-delay: 0.3s; }
</style>